<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\RoomTag\Action\Sidebar;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\SidebarAuthMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\RoomTag\Contract\RoomTagContract;
use MoChat\Plugin\RoomTag\Contract\RoomTagGroupContract;
use MoChat\Plugin\RoomTag\Contract\RoomTagPivotContract;

/**
 * 客户画像-客户群标签列表.
 *
 * Class TagIndex
 * @Controller
 */
class index extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var RoomTagGroupContract
     */
    protected $roomTagGroupService;

    /**
     * @Inject
     * @var RoomTagContract
     */
    protected $roomTagService;

    /**
     * @Inject
     * @var RoomTagPivotContract
     */
    protected $roomTagPivotService;

    /**
     * @Middlewares({
     *     @Middleware(SidebarAuthMiddleware::class)
     * })
     * @RequestMapping(path="/sidebar/roomTag/index", methods="get")
     */
    public function handle(): array
    {
        $user = user();
        # # 判断用户绑定企业信息
        if (! isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        $roomId = (int) $this->request->input('roomId', 0);
        $list = $this->roomTagGroupService->getRoomTagGroupsByCorpId([user()['corpId']], ['id', 'group_name']);
        $roomTag = [];
        if ($roomId > 0) {
            $roomTags = $this->roomTagPivotService->getRoomTagPivotsByRoomIdTagId($roomId, 0, ['room_tag_id']);
            $roomTag = array_column($roomTags, 'roomTagId');
        }
        foreach ($list as $k => $v) {
            $tags = $this->roomTagService->getRoomTagsByGroupIds([$v['id']], ['id', 'name', 'room_tag_group_id']);
            if ($roomId > 0) {
                foreach ($tags as $key => $val) {
                    $tags[$key]['isSelect'] = 0;
                    if (in_array($val['id'], $roomTag, true)) {
                        $tags[$key]['isSelect'] = 1;
                    }
                }
            }
            $list[$k]['tags'] = $tags;
        }
        return $list;
    }

    /**
     * @return string[] 规则
     */
    public function rules(): array
    {
        return [
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    public function messages(): array
    {
        return [
        ];
    }
}
